package it.fuesi.synotools.services.tasks.download;

import android.content.Context;

import java.util.List;

import it.fuesi.synotools.model.base.ErrorObject;
import it.fuesi.synotools.model.base.VoidDataObject;
import it.fuesi.synotools.model.base.VoidResponse;
import it.fuesi.synotools.model.download.DownloadStationClientParameters;
import it.fuesi.synotools.model.download.DownloadTask;
import it.fuesi.synotools.services.client.DownloadStationClient;
import it.fuesi.synotools.services.client.ServiceClientFactory;
import it.fuesi.synotools.services.tasks.base.BaseTask;

/**
 * Created by pascotto on 17/10/14.
 */
public class ClearCompletedTask extends BaseTask<VoidResponse, VoidDataObject, DownloadStationClientParameters> {

    private static final String TAG = ClearCompletedTask.class.getName();

    public ClearCompletedTask(Context context){
        super(context);
    }


    @Override
    protected String getCacheKey() {
        return null;
    }

    @Override
    public VoidResponse run(DownloadStationClientParameters params) throws Exception {

            final VoidResponse response = new VoidResponse();
            response.setSuccess(true);

            publishProgress("Clearing completed tasks");
            final DownloadStationClient client = ServiceClientFactory.getClient(DownloadStationClient.class);

            final List<DownloadTask> list = params.getTasks();

            int fail = 0;

            for(DownloadTask task : list){
                publishProgress("Deleting task: " + task.getTitle());
                final VoidResponse resp = client.deleteTask(task.getId());

                if(!resp.isSuccess())
                    fail++;
            }

            if(fail > 0){
                ErrorObject err = new ErrorObject();
                err.setMessage("Failed to clear " + fail + " tasks");
                response.setSuccess(false);
                response.setError(err);
            }

            return response;


    }


}
